package Adapters;

import java.util.ArrayList;

import fiuba.descuentos.R;

import Entities.Benefit;
import Helpers.ContextHelper;
import Helpers.FileHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class BenefitAdapter extends ArrayAdapter<Benefit>{
	private ArrayList<Benefit> benefits;


	public BenefitAdapter(int textViewResourceId, ArrayList<Benefit> benefits) {
		super(ContextHelper.getContextInstance(), textViewResourceId, benefits);
		this.benefits = benefits;		

	}

	public View getView(int position,
			View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) ContextHelper.getContextInstance()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.benefit_column, null);
		}
		
		Benefit benefit = benefits.get(position);
		if (benefit != null) {			
			
			TextView txtName = (TextView) v.findViewById(R.id.lbl_name);						
			bindLabelWithTitle(txtName,benefit.getName() + " (" + benefit.getCompany() + ")");
			
			TextView txtAddress = (TextView) v.findViewById(R.id.lbl_address);
			String address = benefit.getFullAddress();
			String distance = benefit.getDistance();
			if(distance != null){
				address += " (" + distance + "km)";
			}					
			bindLabelWithTitle(txtAddress,address);
			
			TextView txtDescription = (TextView) v.findViewById(R.id.lbl_description);			
			bindLabelWithTitle(txtDescription,benefit.getDescription());
						

			ImageView logo = (ImageView) v.findViewById(R.id.image);
			logo.setTag(benefit);
			bindViewWithImage(logo ,benefit.getLogo());

		}

		return v;
	}


	private void bindLabelWithTitle(TextView label, String name) {
		label.setText(name);
	}

	private void bindViewWithImage(ImageView imageButton, String logo) {
		try {
			Bitmap bmp = FileHelper.getImageBitMap(logo,"");
			imageButton.setImageBitmap(bmp);
		} catch (Exception e) {

		}
	}
}